package uestc.lj.gulishop.ware.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uestc.lj.common.to.OrderEntityTO;
import uestc.lj.common.to.StockLockedTO;
import uestc.lj.gulishop.ware.service.WareSkuService;

import java.io.IOException;

/**
 * @Author:Crazlee
 * @Date:2021/6/21
 */
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 解锁库存的方法
     * 1.查询数据库关于订单的锁定库存信息
     * 有-->库存锁定成功
     * 2.查询订单情况
     * 无-->创建订单失败，自己回滚，解锁
     * 有-->3. 判断订单的支付情况只有超时才会解锁
     * 无-->库存自己失败，已经回滚无需解锁
     *
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTO to, Message message, Channel channel) throws IOException {
        System.out.println("库存到期，自动解锁库存...");
        try {
            wareSkuService.unLockStock(to);
            // 执行成功之后回复ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 任何异常说明未解锁，直接重新归队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleOrderClosedRelease(OrderEntityTO orderEntityTO, Message message, Channel channel) throws IOException {
        System.out.println("订单已过期，自动解锁库存...");
        try {
            wareSkuService.unLockStock(orderEntityTO);
            // 执行成功之后回复ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 任何异常说明未解锁，直接重新归队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
